import { Injectable, NestMiddleware } from '@nestjs/common';
import { Request, Response, NextFunction } from 'express';

@Injectable()
export class LanguageMiddleware implements NestMiddleware {
    use(req: Request, res: Response, next: NextFunction) {
        // 从查询参数获取语言
        const queryLang = req.query.lang as string;

        // 从请求头获取语言
        const acceptLanguage = req.headers['accept-language'] as string;

        // 从 Cookie 获取语言
        const cookieLang = req.cookies?.language;

        // 语言优先级：查询参数 > Cookie > Accept-Language > 默认英文
        let language = 'en';

        if (queryLang && ['en', 'zh'].includes(queryLang)) {
            language = queryLang;
        } else if (cookieLang && ['en', 'zh'].includes(cookieLang)) {
            language = cookieLang;
        } else if (acceptLanguage) {
            // 解析 Accept-Language 头
            const languages = acceptLanguage
                .split(',')
                .map(lang => lang.split(';')[0].trim().toLowerCase());

            // 检查是否支持中文
            if (languages.some(lang => lang.startsWith('zh'))) {
                language = 'zh';
            }
        }

        // 将语言设置到请求对象中
        (req as any).language = language;

        // 设置响应头
        res.setHeader('Content-Language', language);

        next();
    }
}
